<template>
  <div class='trade txtcolor radius4 flex column h100'>
    <div class="available flex alcenter plr15 partBg radius4 mt4 mr4" v-if="token">
      <p class="ft12 txtgray">可用</p>
      <p class="txtcolor bold">
        <span class="plr10 bdr">{{balance.user_legal}} {{tradeData.legal_name}}</span>
        <span class="ml5">{{balance.user_currency}} {{tradeData.currency_name}}</span>
      </p>
    </div>
    <div v-else class="available flex alcenter plr15 partBg radius4 mt4 mr4">
      <p><span class="blue">登录</span> 或 <span class="blue">注册</span> 后交易</p>
    </div>
    <div class="mt4 mr4">
      <div class="toptitle ratop fw0 flex ft16 txtgray">
        <p :class="['pointer',{'active':current==0}]" @click="current=0,disabled=false">限价交易</p>
        <p :class="['pointer','ml40',{'active':current==1}]" @click="current=1,disabled=true">市价交易</p>
      </div>
      <div class="flex1 flex rabom tradboxs partBg ft12">
        <!-- 买入 -->
        <div class="flex1 tradlf">
          <!-- <div class="canuse bdb">可用 1000 USDT</div> -->
          <label class="bd radius4 plr15 ptb4 flex between alcenter" :class="{'bdactive':active==1}">
            <div class="label flex flex1 alcenter">
              <div class="txtgray">买入价</div>
              <input type="text" class="flex1 pl10" v-if="!disabled" v-model="buyprice" @keyup="limitBuy()" @focus="active=1" @blur="active=0">
              <input type="button" class="txtgray flex1 ft14 disabled" disabled v-else value="以市场最优价格买入">
            </div>
            <span class="txtgray">{{tradeData.legal_name}}</span>
          </label>
          <label class="bd radius4 plr15 ptb4 flex between alcenter mt8" :class="{'bdactive':active==2}">
            <div class="label flex flex1 alcenter">
              <div class="txtgray">买入量</div>
              <input type="text" class="flex1 pl10" v-model="buynum" @focus="active=2" @blur="active=0">
            </div>  
            <span class="txtgray">{{tradeData.currency_name}}</span>
          </label>
          <div class="btnbox flex mt5">
            <button v-for="(item,index) in percentBuy" :class="['pointer',{'ml5':index>0}]" @click="changeBuy(index,item)">{{item}}%</button>
          </div>
          <div class="mt15">
            <span class="ft12 txtgray">交易额:</span>
            <span class="ft14">{{buyTotal | Fixed8}} {{tradeData.legal_name}}</span> 
          </div>
          <input type="button" class="bggreen mt8 btn pointer" :value="'买入'+tradeData.currency_name" @click="confirm('buy')" v-if="token">
          <input type="button" class="bggreen mt8 btn pointer" value="登录或注册后交易" v-else>
        </div> 
        <!-- 卖出 -->
        <div class="flex1 tradrt">
          <!-- <div class="canuse bdb">可用 1000 ETH</div> -->
          <label class="bd radius4 plr15 ptb4 flex between alcenter" :class="{'bdactive':active==3}">
            <div class="label flex flex1 alcenter">
              <div class="txtgray">卖出价</div>
              <input type="text" class="flex1 pl10" v-if="!disabled" v-model="sellprice" @keyup="limitSell()" @focus="active=3" @blur="active=0">
              <input type="button" class="txtgray ft14 flex1 disabled" disabled v-else value="以市场最优价格卖出">
            </div>
            <span class="txtgray">{{tradeData.legal_name}}</span>
          </label>
          <label class="bd radius4 plr15 ptb4 flex between alcenter mt8" :class="{'bdactive':active==4}">
            <div class="label flex flex1 alcenter">
              <div class="txtgray">卖出量</div>
              <input type="text" class="flex1 pl10" v-model="sellnum" @focus="active=4" @blur="active=0">
            </div>
            <span class="txtgray">{{tradeData.currency_name}}</span>
          </label>
          <div class="btnbox flex mt5">
            <button v-for="(item,index) in percentSell" :class="['pointer',{'ml5':index>0}]" @click="changeSell(index,item)">{{item}}%</button>
          </div>
          <div class="mt15">
            <span class="ft12 txtgray">交易额:</span>
            <span class="ft14">{{sellTotal | Fixed8}} {{tradeData.legal_name}}</span> 
          </div>
          <input type="button" class="bgred mt8 btn pointer" :value="'卖出'+tradeData.currency_name" @click="confirm('sell')" v-if="token">
          <input type="button" class="bgred mt8 btn pointer" value="登录或注册后交易" v-else>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from "vuex";
export default {
  name:'trade',
  data () {
    return {
      current:0,
      active:0,
      disabled:false,
      buyprice:'',
      buynum:'',
      sellprice:'',
      sellnum:'',
      balance:{user_currency:'--',user_legal:'--',last_price:""},
      percentBuy:[25,50,75,100],
      percentSell:[25,50,75,100],
    };
  },
  created(){

  },
  computed: {
    ...mapState({
      tradeData: state => state.tradeData,
    }),
    ...mapGetters({
      'token': 'getToken'
    }),
    buyTotal(){
      let total = (this.buyprice * this.buynum) || 0.0000;
      return total;
    },
    sellTotal(){
      let total = (this.sellprice * this.sellnum) || 0.0000;
      return total;
    }
  },
  mounted(){
    var that = this;
    eventBus.$on("changePrice", function(data){//监听点击盘口价格
      that.buyprice=data;
      that.sellprice=data;
    });
    eventBus.$on("userBalance", function(data){//监听用户可用余额及最后新价(页面刷新可少请求一次)
      that.balance = data;
      that.buyprice = data.last_price;
      that.sellprice = data.last_price;
    });
  },
  methods:{
    limitBuy(){
      this.buyprice=this.buyprice.toString().match(/^\d+(?:\.\d{0,8})?/)//只允许输入数字并且限制小数点位数
    },
    limitSell(){
      this.sellprice=this.sellprice.toString().match(/^\d+(?:\.\d{0,8})?/)//只允许输入数字并且限制小数点位数
    },
    // 价格百分比
    changeBuy(index,percent){
      var a = (this.balance.user_legal/this.buyprice);
      var b = ( parseInt( a * 10000 ) / 10000 ).toFixed(4);//不四舍五入保留四位小数
      this.buynum = (b*percent/100).toFixed(4);
    },
    changeSell(index,percent){
      this.sellnum = (this.balance.user_currency*percent/100).toFixed(4);
    },
    confirm(type){//确认/输密码/判断买入卖出
      var that = this;
      if(type=='buy'){
        if(!that.buyprice){
          return that.$message({type: 'info',message: '请输入买入价'});
        }
        if(!that.buynum){
          return that.$message({type: 'info',message: '请输入买入量'});
        }
      }
      if(type=='sell'){
        if(!that.sellprice){
          return that.$message({type: 'info',message: '请输入卖出价'});
        }
        if(!that.sellnum){
          return that.$message({type: 'info',message: '请输入卖出量'});
        }
      }
      that.$prompt('请输入安全密码', '提示', {//安全密码
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if(value){
          that.upData(type,value)//提交
        }
      })
      .catch(() => {
        that.$message({type: 'info',message: '取消输入'});
      });
    },
    upData(type,password){ 
      let that = this;
      var url,price,num;
      if(type=='buy'){
        url = 'transaction/in';
        price = that.buyprice;
        num = that.buynum;
      }
      if(type=='sell'){
        url = 'transaction/out';
        price = that.sellprice;
        num = that.sellnum;
      }
      var legal_id = that.tradeData.legal_id;
      var currency_id = that.tradeData.currency_id;
      console.log(type,password)
      that.axios.post("/api/"+url, {legal_id,currency_id,price,num,password}).then(res => {
          that.$message({type: 'info',message: res.data.message});
          if (res.data.type == "ok") {
            that.getDeal();//获取可用余额
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getDeal() {//获取可用余额(下单成功调用一下)
      let that = this;
      that.axios
        .post("/api/transaction/deal", {
          legal_id: that.tradeData.legal_id,
          currency_id: that.tradeData.currency_id
        })
        .then(res => {
          if (res.data.type == "ok") {
            var data = res.data.message;
            var balance = {
                user_legal:data.user_legal,
                user_currency:data.user_currency,
                last_price:data.last_price
            }
            that.balance = balance;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
  }
}

</script>
<style lang='scss' scoped>
.trade{
  .available{
    height: 40px;
    line-height: 40px;
  }
  .tradboxs{
    padding: 16px;
    .tradlf{ padding-right: 15px;}
    .tradrt{ padding-left: 15px;}
    .canuse{height: 50px;line-height: 50px;}
    input{height: 24px;width: 100%;}
    .bordercolor{border-color: #4e5b85}
    .disabled{border-color: transparent;}
    .btnbox button{
      color: #7085ac;
      flex: 1;
      height: 24px;
      border-radius: 3px;
      border: 1px solid #2e3753;
    }
    .btnbox button:hover{
      color: #357ce1;
      border-color: #357ce1;
    }
    .btn{height: 34px;border-radius: 4px}
  }
  
}
</style>